<?php
/* 
 * Active record implementations
 * easy example of database persistency
 * this class make use of reflection to persist
 * all protected propreties of objects
 * 
 */

class ActiveRecord implements BusinessAdapter
{
    private $status = 'insert';

    /**
     *
     * @param <type> $name
     * @param <type> $arguments
     */
    public function __call($name, $arguments){}

    /**
     *
     * @return <type>
     */
    public function getName(){
        return __CLASS__;
    }

    /**
     * Iplementation of the update method the observer is listening to
     *
     * @param <type> $object
     * @return <type>
     */
    public function update(BusinessObject $object){
        $ref = new ReflectionClass($object);
        $refProps = $ref->getProperties(ReflectionProperty::IS_PROTECTED);
        // build a property key => value array
        $properties = array();
        foreach($refProps as $property){
            if($property->getName() != 'primaryKey'){
                /*
                 * as from php.net docuentation this should work but does not
                 *  php version fault
                 */
                //$property->setAccessible(true);
                //$properties[$property->getName()] = $property->getValue($object) ;
                $method = "get".ucfirst($property->getName());
                $properties[$property->getName()] = $object->{$method}() ;
            }
        }
        $conn = Connection::getInstance();
        if($this->status == 'insert'){
            $method = 'set'.ucfirst($object->getPrimarykey());
            $primaryKeyValue = $conn->insert($properties, get_class($object));
            //$object->{$method}() = $primaryKeyValue;
            return;
        }
        else{
            return $conn->update($properties, get_class($object), $object->primarykey);
        }
    }

    /**
     * Get Object from the connection
     *
     * @param <type> $class
     * @param <type> $id
     * @return <type>
     */
    public function getObject($class, $id){
        $conn = Connection::getInstance();
        return $conn->getObject($class, $id);
    }

    /**
     * The Active record class get some relevant information
     * from the state of the object
     * @param <type> $object
     */
    public function getObjectState($object){
        if($this->getObjectPrimaryKeyValue($object) !== null){
            $this->status = 'update';
        }
    }

    /**
     * get the name of the primary key of the object
     * @param <type> $object
     * @return <type> 
     */
    private function getObjectPrimaryKeyValue($object){
        $primatyKey = $object->primaryKey;
        return $object->$primatyKey;
    }
}